<template>
  <!-- 诉讼立案 -->
  <section class="component lwasuit-follow">
    <!-- 步骤条区域 -->
    <el-steps :active="currentStep.active" align-center style="margin-bottom: 20px;" finish-status="success" process-status="finish">
      <el-step v-for="(title, index) of steps" :title="title" :key="index"></el-step>
    </el-steps>
    <!-- 表单区域 -->
    <component :is="currentComponent" :follower="rowData.assistCollectorName" :isView="isView" ref="current-comp"></component>
    <!-- 按钮区域 -->
    <div class="operate-buttons">
      <el-button v-show="isShow('revoke')" @click="withdraw(lawsuitStatus.withdrawal)">撤诉</el-button>
      <el-button v-show="isShow('previous')" @click="onPrevious()">上一步</el-button>
      <el-button v-show="isShow('save')" @click="onSave()" :loading="saveLoading">保存</el-button>
      <el-button v-show="isShow('next')" @click="next()">下一步</el-button>
      <el-button v-show="isShow('close')" @click="withdraw(lawsuitStatus.closingCase)">结案</el-button>
      <el-button v-show="isShow('end')" @click="next('END')">执行终结</el-button>
      <el-button v-show="isShow('allot')" @click="next('TAKE')">参与分配</el-button>
      <el-button v-show="isShow('complete')" @click="onComplete()">完成</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Emit, Prop ,Watch} from "vue-property-decorator";
import { Getter, State } from "vuex-class";
import FileUpload from "~/components/common/file-upload.vue"
import LawsuitFollowKind from "./lawsuit-follow-kind/index";
import { lawsuitItem, lawsuitStatus } from "./lawsuit.config";
import { OutsourceLawsuitService } from "~/services/domain-service/outsource-lawsuit-manage-index.service";

@Component({
  components: {
    FileUpload, 
    ...LawsuitFollowKind
  }
})
export default class LawsuitFollow extends Vue {
  @Dependencies(OutsourceLawsuitService)
  private outsourceLawsuitService: OutsourceLawsuitService
  @State
  private userData
  private lawsuitStatus: any = lawsuitStatus

  @Prop()
  private rowData;
  @Prop({default: false})
  private isView;
  @Prop({
    default: {
      kind: '',
      status: '',
    }
  })
  private lawsuit

  
  // 步骤
  private currentStep: any = {
    active:  0,
    code: '',
  }
  // 步骤条
  private steps: any[] = [];
  // 当前步骤是否保存过
  private isSave: boolean = false;
  private currentComponent: string = '';
  private saveLoading: boolean = false;

  @Emit("refreshData")
  private refreshData() {}
  @Emit("close")
  private close() {}

  /**
   * 计算当前应该显示的页面
   */
  @Watch("currentStep.active", {deep: true})
  private currentComp() {
    const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
    const step = steps.find(v => v.active === this.currentStep.active && v.code === this.currentStep.code)
    this.currentComponent = step ? step.comp : ''
  }

  /**
   * 控制按钮的显示
   */
  private isShow(btn) {
    const items = lawsuitItem.find(v => v.kind === this.lawsuit.kind)
    if (!items) return false
    const steps = items.steps
    if (!steps) return false 
    const butType = this.isView ? 'viewButtons' : 'buttons'
    const buttons = steps.find(v => v.active === this.currentStep.active)[butType]
    if (this.lawsuit.status === lawsuitStatus.end || this.lawsuit.status === lawsuitStatus.take) {
      const filteItem = this.lawsuit.status === lawsuitStatus.end ? 'allot' : 'end'
      const tempButtons = buttons.filter(v => v !== filteItem)
      return tempButtons.includes(btn)
    }
    return buttons.includes(btn)
  }

  /**
   * 获取当前案件步骤
   */
  private getCourtInfoStep(code?) {
    const params = {id: this.rowData.id, lawerStatus: code}
    this.outsourceLawsuitService.getCourtInfoStep(params).subscribe(
      (data) => {
        if (!data) {
          this.isSave = false
          this.$nextTick(() => {
            const comp = (this.$refs['current-comp'] as any)
            comp.reset()
          })
          return
        }
        this.isSave = !!data.lawerStatus
        if (!code && !this.isView) {
          const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
          const step = steps.find(v => v.code === data.lawerStatus)
          this.currentStep = step ? {code: step.code, active: step.active} : {code: steps.find(v => v.active === 0).code, active: 0}
        }
        this.$nextTick(() => {
          (this.$refs['current-comp'] as any).revertData(data)
        })
      }
    )
  }


  /**
   * 上一步
   */
  private onPrevious() {
    if (this.lawsuit.status !== lawsuitStatus.end && this.lawsuit.status !== lawsuitStatus.take) {
      this.updateSteps()
    }
    const step = this.getStep(this.currentStep.active - 1)
    this.getCourtInfoStep(step.code)
    this.currentStep = {code: step.code, active: this.currentStep.active - 1}
  }

  /**
   * 保存
   */
  private async onSave() {
    
    try {
      const data = await this.getData()
      if (!data) return
      this.saveLoading = true
      const params = {
        ...data,
        caseAssistId: this.rowData.id, 
        lawsuitFollowType: this.lawsuit.kind,
        lawerStatus: this.currentStep.code
      }
      this.outsourceLawsuitService.saveCourtInfo(params).subscribe(
        () => {
          this.isSave = true
          // 保存之后更新lawsuitStatus为最新的状态
          const step = this.getStepByCode(this.currentStep.code)
          const status = this.getStepByCode(this.lawsuit.status)
          if (step.active > status.active) {
            this.lawsuit.status = step.code
          }
          this.saveLoading = false
          this.$message.success("操作成功")
        }
      )
    } catch(e) {
      this.saveLoading = true
      this.$message.error("操作失败，请重试")
    }
  }

  /**
   * 下一步/执行终结/参与分配
   */
  private next(type?) {
    if (!this.isView && !this.isSave) {
      this.$message.error("此步骤未保存,请保存之后执行下一步")
      return
    }
    const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
    let code
    if (!type) {
      code = steps.find(v => v.active === this.currentStep.active + 1).code
    } else {
      const tempStep = type === "TAKE" ? lawsuitStatus.take : lawsuitStatus.end
      code = steps.find(v => v.active === this.currentStep.active + 1 && v.code === tempStep).code
    }
    this.getCourtInfoStep(code)
    if (type) this.updateSteps(type) // 如果是执行终结/参与分配则更新步骤条
    this.currentStep = {code, active: this.currentStep.active + 1}
  }

  /**
   * 撤诉/结案
   */
  private withdraw(status) {
    this.outsourceLawsuitService.withdraw({caseId: this.rowData.id, lawerStatus: status}).subscribe(
      data => this.success()
    )
  }

  /**
   * 完成
   */
  private onComplete() {
    if (!this.isSave) {
      this.$message.error("此步骤未保存,请保存之后再点击完成")
      return
    }
    this.outsourceLawsuitService.withdraw({caseId: this.rowData.id, lawerStatus: this.currentStep.code}).subscribe(
      data => this.success()
    )
  }

  /**
   * 获取表单数据
   */
  private async getData() {
    const currentComp: any = this.$refs["current-comp"]
    const data = await currentComp.getData()
    return data
  }

  private success() {
    this.$message.success("操作成功")
    this.refreshData()
    this.close()
  }

  /**
   * 弹框打开时页面数据刷新
   */
  private async refresh(lawerStatus?) {
    if (this.isView) {
      const step: any = this.getStep(0)
      this.getCourtInfoStep(step.code)
      this.currentStep = {code: step.code, active: step.active}
    } else {
      this.getCourtInfoStep()
    }
    let type
    if(lawerStatus === "END") type = "END"
    if(lawerStatus === "TAKE")  type = "TAKE"
    this.updateSteps(type)
  }

  /**
   * 计算页面步骤条内容
   */
  private updateSteps(type?) {
    const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
    if (!type) {
      const tempSteps: string[] = []
      for (const step of steps) {
        tempSteps[step.active] = tempSteps[step.active] ? tempSteps[step.active] + "/" + step.name : step.name
      }
      this.steps = tempSteps
      return
    } 
    // 执行终结/参与分配
    const tempStep = type === "END" ? lawsuitStatus.end : lawsuitStatus.take
    const endStep = steps.find(v => v.code === tempStep)
    const tempSteps: string[] = []
    for (const step of steps) {
      if (step.active !== endStep.active) {
        tempSteps.push(step.name)
      } else if (step.code === tempStep) {
        tempSteps.push(step.name)
      }
    }
    this.steps = tempSteps
  }

  private getStep(active: number): any {
    const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
    const step = steps.find(v => v.active === active)
    if (!step) return {}
    return {
      name: step.name,
      code: step.code,
      active: step.active
    }
  }

  private getStepByCode(code: string): any {
    const steps = lawsuitItem.find(v => v.kind === this.lawsuit.kind).steps
    const step = steps.find(v => v.code === code)
    if (!step) return {}
    return {
      name: step.name,
      code: step.code,
      active: step.active
    }
  }

}
</script>

<style lang="less" scoped>

</style>